package com.pet.server.ext.action.find;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Logger;
import com.pet.server.ext.Result;
import com.pet.server.ext.constants.BaseAttribute;
import com.pet.server.ext.data.Constant;
import com.pet.server.ext.data.PetInfo;
import com.pet.server.ext.service.ArticleService;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.JsonUtil;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.RandomCollection;
import com.pet.server.ext.util.StringUtil;
import com.pet.server.ext.util.cache.ConstantUtil;
import com.pet.server.ext.util.cache.PetCache;

public class Article extends ActionBase{

	private static Logger logger = Logger.getLogger(Article.class);
	private String pet_brands,age_cates,article_cates;
	private Integer article_size,subject_size;
	private String[] brands,cates,articleCate;
    private List<Integer> ids=new ArrayList<Integer>();
	

	public Article(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
       pet_brands=params.getFieldValue("pet_brands");
       age_cates=params.getFieldValue("age_cates");
       article_cates=params.getFieldValue("article_cates");
       article_size=NumberUtil.getInteger(params.getFieldValue("article_size"), 5);
       //System.out.println(article_size);
       if(!StringUtil.isEmpty(pet_brands)){
    	   brands = pet_brands.split(",");
       }
       if(!StringUtil.isEmpty(age_cates)){
    	   cates = age_cates.split(",");
       }
       if(!StringUtil.isEmpty(article_cates)){
    	   articleCate = article_cates.split(",");
       }
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		List<PetInfo> petlist = userService.queryPetInfoByUserId(user.user_id);
		Constant conts = ConstantUtil.getInstance().findConstant("004");

		List<com.pet.server.ext.data.Article> article_list = PetCache.queryArticles4cache();
		StringBuffer brands=new StringBuffer("(000000");
		StringBuffer ages=new StringBuffer("(000000");
		for(PetInfo p:petlist){
			Integer months = DateUtil.getMonth(p.birthday, new Date());
			String ageCate=null;
			if(conts!=null){
				 ageCate = getAgeCate(conts.list, months);				
			}
			ageCate = StringUtil.dealNull(ageCate, "0000");
			brands.append("|"+p.breed);
			ages.append("|"+ageCate);
			
		}
		brands.append(")");
		ages.append(")");
		
		RandomCollection<com.pet.server.ext.data.Article> random = pickerArticle(article_list,brands.toString(),ages.toString());
		
		List<com.pet.server.ext.data.Article> plist = new ArrayList<com.pet.server.ext.data.Article>();
		while(plist.size()<article_size&&random.size()>0){
			com.pet.server.ext.data.Article a = random.removeNext();
			if(null!=a){
				plist.add(a);
			}
			//System.out.println(plist.size()+" "+random.size());
		}
		//List<com.pet.server.ext.data.Article> picker_list = random.removeNext(article_size);
		
		JSONArray array = new JSONArray();		
		for(com.pet.server.ext.data.Article cle:plist){
			JSONObject o = new JSONObject();
			o.put("article_id", cle.article_id);
			o.put("title", cle.getTitle());
			o.put("description", cle.description);
			o.put("create_time", JsonUtil.getTime(cle.getCreate_time()));
			o.put("view_type", cle.view_type);
			o.put("url", BaseAttribute.article_url+cle.article_id);
			o.put("cate", cle.cate);
			o.put("cate_name",ConstantUtil.getInstance().getName(cle.cate));
			JSONArray images = new JSONArray();
			if(BaseAttribute.view_type.grid.toString().equals(cle.view_type)){
				if(!StringUtil.isEmpty(cle.image1)){images.add(cle.image1);}
				if(!StringUtil.isEmpty(cle.image2)){images.add(cle.image2);}
				if(!StringUtil.isEmpty(cle.image3)){images.add(cle.image3);}
			}else if(BaseAttribute.view_type.small.toString().equals(cle.view_type)){
				if(!StringUtil.isEmpty(cle.image1)){images.add(cle.image1);}
			}if(BaseAttribute.view_type.large.toString().equals(cle.view_type)){
				if(!StringUtil.isEmpty(cle.image1)){images.add(cle.image1);}
			}
			o.put("images", images);
			array.add(o);
		}
		data.put("list", array);
		Result result = new Result();
		result.put("data", data);
	    return result;
	}
	public RandomCollection<com.pet.server.ext.data.Article> pickerArticle( List<com.pet.server.ext.data.Article> list,String brands,String ages){
		RandomCollection<com.pet.server.ext.data.Article> random = new RandomCollection<com.pet.server.ext.data.Article>();
		System.out.println(brands+"  "+ages); 
		for(com.pet.server.ext.data.Article acl:list){
            Integer weight = 1;
            
            String brandReg = "^.*"+StringUtil.dealNull(acl.pet_cate,"111111")+".*$";
            String ageReg = "^.*"+StringUtil.dealNull(acl.age_cate,"111111")+".*$";

            logger.logInfo(brands+".matches("+brandReg+")");
            logger.logInfo(ages+".matches("+ageReg+")");
            
            boolean brand_match = brands.matches(brandReg);
            boolean ages_match = ages.matches(ageReg);  
            
			if(brand_match&&ages_match){
				weight=10000;
			}else if(brand_match||ages_match){
				weight=100;
			}
			random.add(weight, acl);
		 }
		return random;
	}
	public String getAgeCate(List<Constant> list,int months){
		for(Constant c:list){
			String[] strs = StringUtil.dealNull(c.val).split(",");
			if(strs.length==2){
				Integer begin = NumberUtil.getInteger(strs[0]);
				Integer end = NumberUtil.getInteger(strs[1]);
				if(begin<months&&end>=months){
					return c.getCode();
				}
			}
		}
		return null;
	}
}
